package com.example.financecollegeorderdish.ui

import android.content.Context
import android.content.Intent
import android.view.View
import android.widget.TextView
import com.blankj.utilcode.util.UriUtils
import com.bumptech.glide.Glide
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.drake.channel.receiveEvent
import com.example.financecollegeorderdish.AppApplication
import com.example.financecollegeorderdish.R
import com.example.financecollegeorderdish.databinding.ActivityInputBinding
import com.example.financecollegeorderdish.db.bean.DishBean
import com.example.financecollegeorderdish.db.bean.MineralBean
import com.example.financecollegeorderdish.db.bean.VitaminBean
import com.example.financecollegeorderdish.util.SelectPhotoContract
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lxj.xpopup.XPopup
import com.quyunshuo.androidbaseframemvvm.base.mvvm.vm.EmptyViewModel
import com.wuhao.lib_base.mvvm.v.BaseActivity
import com.wuhao.lib_common.utils.LoggerHelper
import com.wuhao.lib_common.utils.NotNullHelper
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.schedulers.Schedulers
import java.lang.reflect.Type

class InputActivity : BaseActivity<ActivityInputBinding, EmptyViewModel>() {
    override val mViewModel: EmptyViewModel
            by lazy { EmptyViewModel() }

    override fun createVB(): ActivityInputBinding = ActivityInputBinding.inflate(layoutInflater)

    override fun initObserve() {
    }

    override fun initRequestData() {
    }

    var healthTagList: MutableList<String> = mutableListOf()//健康标签
    var rawMaterialTagList: MutableList<String> = mutableListOf()//健康标签
    var imgPath: String = ""
    var isEditMode = false
    var primaryKey = -1L

    override fun ActivityInputBinding.initView() {
        primaryKey = intent.getLongExtra("primaryKey", -1L)!!//获取用户姓名
        if (primaryKey != -1L) {
            isEditMode = true
            getDataByPrimaryKey(primaryKey)
        }

        mBinding.btnCancel.setOnClickListener { finish() }
        mBinding.btnOk.setOnClickListener {
            if (isEditMode) {
                isEditMode = false
                updateOne()
            } else {
                insertOne()
            }
        }
        mBinding.addGroup.setOnClickListener { selectPhotoLauncher.launch(null) }
        mBinding.imgDish.setOnLongClickListener {
            isDeleImg()
            true
        }
        mBinding.finish.setOnClickListener { finish() }
        initHealth()
        initRawMaterial()
        mBinding.addVitaminTag.setOnClickListener {
//            XPopup.Builder(this@InputActivity)
//                .autoOpenSoftInput(false)
//                .autoFocusEditText(false)
//                .dismissOnTouchOutside(false)
//                .asCustom(VitaminInputDialog(this@InputActivity))
//                .show()
            startActivity(VitaminInputActivity::class.java)
        }
        mBinding.addMineralTag.setOnClickListener {
//            XPopup.Builder(this@InputActivity)
//                .autoOpenSoftInput(false)
//                .autoFocusEditText(false)
//                .moveUpToKeyboard(false)
//                .dismissOnTouchOutside(false)
//                .asCustom(MineralInputDialog(this@InputActivity))
//                .show()
            startActivity(MineralInputActivity::class.java)
        }
        receiveEvent<MineralBean> {
            iron = it.iron
            manganese = it.manganese
            zinc = it.zinc
            copper = it.copper
            potassium = it.potassium
            phosphorus = it.phosphorus
            sodium = it.sodium
            calcium = it.calcium
            selenium = it.selenium
            magnesium = it.magnesium
            mBinding.mineralTag.setText("已经输入矿物质数据")
        }
        receiveEvent<VitaminBean> {
            VitaminB1 = it.VitaminB1
            VitaminB2 = it.VitaminB2
            VitaminB3 = it.VitaminB3
            VitaminB5 = it.VitaminB5
            VitaminB6 = it.VitaminB6
            VitaminB7 = it.VitaminB7
            VitaminB9 = it.VitaminB9
            VitaminB12 = it.VitaminB12
            VitaminC = it.VitaminC
            VitaminA = it.VitaminA
            VitaminD = it.VitaminD
            VitaminE = it.VitaminE
            VitaminK = it.VitaminK
            mBinding.vitaminTag.setText("已经输入维他命数据")
        }
    }

    /**
     * 前往相册选择照片，并前往裁剪
     */
    private val selectPhotoLauncher = (this as InputActivity).registerForActivityResult(
        SelectPhotoContract()
    ) { uri ->
        uri.let {
            if (uri != null) {
                setImageAddInVisible(UriUtils.uri2File(uri).absolutePath)
            } else {
                setImageAddVisible()
                showError("选取失败")
            }
        }
    }

    /**
     * 添加图片按钮设置不可见
     */
    private fun setImageAddInVisible(path: String) {
        imgPath = path
        mBinding.addGroup.visibility = View.GONE
        mBinding.imgDish.visibility = View.VISIBLE
        LoggerHelper.e(imgPath)
        Glide.with(this@InputActivity)
            .load(imgPath)
            .into(mBinding.imgDish)
    }

    /**
     * 添加图片按钮设置可见
     */
    private fun setImageAddVisible() {
        mBinding.addGroup.visibility = View.VISIBLE
        mBinding.imgDish.visibility = View.GONE
        imgPath = ""
    }

    /**
     * 菜品图片删除提示
     */
    private fun isDeleImg() {
        XPopup.Builder(this@InputActivity).asConfirm(
            "提醒", "确认删除图片吗？"
        ) {
            setImageAddVisible()
        }
            .show()
    }

    /**
     * 初始化健康特征
     */
    fun initHealth() {
        mBinding.addHealthTag.setOnClickListener {
            val text = mBinding.healthTag.text
            if (text!!.isNotEmpty()) {
                healthTagList.add(text.toString())
                mBinding.healthTag.setText("")
            }
            mBinding.healthTagRv.models = healthTagList
        }
        mBinding.healthTagRv.apply {
            layoutManager = FlexboxLayoutManager(context)
            setup {
                addType<String>(R.layout.rv_item_tag)
                onBind {
                    val tag = findView<TextView>(R.id.tag)
                    val model = getModel<String>()
                    tag.text = model
                }
                onClick(R.id.tag_delete) {
                    when (it) {
                        R.id.tag_delete -> {
                            if (healthTagList[modelPosition].isNotEmpty()) {
                                healthTagList.removeAt(modelPosition)
                            }
                            mBinding.healthTagRv.models = healthTagList
                        }

                        else -> {}
                    }
                }
            }.models = healthTagList
        }
    }

    /**
     * 初始化健康特征
     */
    fun initRawMaterial() {
        mBinding.addRawMaterialTag.setOnClickListener {
            val text = mBinding.rawMaterialTag.text
            if (text!!.isNotEmpty()) {
                rawMaterialTagList.add(text.toString())
                mBinding.rawMaterialTag.setText("")
            }
            mBinding.rawMaterialTagRv.models = rawMaterialTagList
        }
        mBinding.rawMaterialTagRv.apply {
            layoutManager = FlexboxLayoutManager(context)
            setup {
                addType<String>(R.layout.rv_item_tag)
                onBind {
                    val tag = findView<TextView>(R.id.tag)
                    val model = getModel<String>()
                    tag.text = model
                }
                onClick(R.id.tag_delete) {
                    when (it) {
                        R.id.tag_delete -> {
                            if (rawMaterialTagList[modelPosition].isNotEmpty()) {
                                rawMaterialTagList.removeAt(modelPosition)
                            }
                            mBinding.healthTagRv.models = rawMaterialTagList
                        }

                        else -> {}
                    }
                }
            }.models = rawMaterialTagList
        }
    }


    fun insertOne() {
        val newOne = DishBean(
            null,
            mBinding.name.text.toString(),
            mBinding.introduce.text.toString(),
            mBinding.taste.text.toString(),
            mBinding.calorie.text.toString(),
            mBinding.protein.text.toString(),
            mBinding.sugar.text.toString(),
            mBinding.fat.text.toString(),
            mBinding.price.text.toString(),
            mBinding.purine.text.toString(),
            mBinding.heat.text.toString(),
            mBinding.dietaryFiber.text.toString(),
            mBinding.cholesterol.text.toString(),
            Gson().toJson(healthTagList),
            if (NotNullHelper.notEmpty(imgPath)) {
                imgPath
            } else {
                ""
            },
            Gson().toJson(rawMaterialTagList),
            mBinding.cookMethod.text.toString(),
            mBinding.cookSkill.text.toString(),
            iron,
            manganese,
            zinc,
            copper,
            potassium,
            phosphorus,
            sodium,
            calcium,
            selenium,
            magnesium,
            VitaminB1,
            VitaminB2,
            VitaminB3,
            VitaminB5,
            VitaminB6,
            VitaminB7,
            VitaminB9,
            VitaminB12,
            VitaminC,
            VitaminA,
            VitaminD,
            VitaminE,
            VitaminK,
        )

        newRx.add(Observable.create<Boolean> { data ->
            val app = application as AppApplication
            val dao = app.room!!.dishBeanDao()
            val primaryKey = dao.insertOne(newOne)
            data.onNext(primaryKey > 0)
        }.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
            .subscribe((Consumer<Boolean> { _: Boolean? ->
                showSuccess("新增菜品成功")
                clearAll()
            }), (Consumer<Throwable> { throwable: Throwable? ->
                showError("新增菜品失败")
            })
            )
        )
    }

    fun updateOne() {
        val updateOne = DishBean(
            primaryKey,
            mBinding.name.text.toString(),
            mBinding.introduce.text.toString(),
            mBinding.taste.text.toString(),
            mBinding.calorie.text.toString(),
            mBinding.protein.text.toString(),
            mBinding.sugar.text.toString(),
            mBinding.fat.text.toString(),
            mBinding.price.text.toString(),
            mBinding.purine.text.toString(),
            mBinding.heat.text.toString(),
            mBinding.dietaryFiber.text.toString(),
            mBinding.cholesterol.text.toString(),
            Gson().toJson(healthTagList),
            if (NotNullHelper.notEmpty(imgPath)) {
                imgPath
            } else {
                ""
            },
            Gson().toJson(rawMaterialTagList),
            mBinding.cookMethod.text.toString(),
            mBinding.cookSkill.text.toString(),
            iron,
            manganese,
            zinc,
            copper,
            potassium,
            phosphorus,
            sodium,
            calcium,
            selenium,
            magnesium,
            VitaminB1,
            VitaminB2,
            VitaminB3,
            VitaminB5,
            VitaminB6,
            VitaminB7,
            VitaminB9,
            VitaminB12,
            VitaminC,
            VitaminA,
            VitaminD,
            VitaminE,
            VitaminK,
        )

        newRx.add(Observable.create<Boolean> { data ->
            val app = application as AppApplication
            val dao = app.room!!.dishBeanDao()
            val primaryKey = dao.updateOne(updateOne)
            data.onNext(primaryKey > 0)
        }.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
            .subscribe((Consumer<Boolean> { _: Boolean? ->
                showSuccess("修改菜品成功")
                clearAll()
            }), (Consumer<Throwable> { throwable: Throwable? ->
                showError("修改菜品失败")
            })
            )
        )
    }

    private fun clearAll() {
        mBinding.name.setText(getText(R.string.empty))
        mBinding.introduce.setText(getText(R.string.empty))
        mBinding.taste.setText(getText(R.string.empty))
        mBinding.calorie.setText(getText(R.string.empty))
        mBinding.protein.setText(getText(R.string.empty))
        mBinding.sugar.setText(getText(R.string.empty))
        mBinding.fat.setText(getText(R.string.empty))
        mBinding.price.setText(getText(R.string.empty))
        mBinding.purine.setText(getText(R.string.empty))
        mBinding.heat.setText(getText(R.string.empty))
        mBinding.dietaryFiber.setText(getText(R.string.empty))
        mBinding.cholesterol.setText(getText(R.string.empty))
        healthTagList = mutableListOf()
        mBinding.healthTagRv.models = healthTagList
        setImageAddVisible()
        rawMaterialTagList = mutableListOf()
        mBinding.rawMaterialTagRv.models = rawMaterialTagList
        mBinding.cookMethod.setText(getText(R.string.empty))
        mBinding.cookSkill.setText(getText(R.string.empty))
        iron = ""
        manganese = ""
        zinc = ""
        copper = ""
        potassium = ""
        phosphorus = ""
        sodium = ""
        calcium = ""
        selenium = ""
        magnesium = ""
        VitaminB1 = ""
        VitaminB2 = ""
        VitaminB3 = ""
        VitaminB5 = ""
        VitaminB6 = ""
        VitaminB7 = ""
        VitaminB9 = ""
        VitaminB12 = ""
        VitaminC = ""
        VitaminA = ""
        VitaminD = ""
        VitaminE = ""
        VitaminK = ""
    }

    var iron: String = ""//铁
    var manganese: String = ""//锰
    var zinc: String = ""//锌
    var copper: String = ""//铜
    var potassium: String = ""//钾
    var phosphorus: String = ""//磷
    var sodium: String = ""//钠
    var calcium: String = ""//钙
    var selenium: String = ""//硒
    var magnesium: String = ""//镁

    var VitaminB1: String = ""//维生素 B1（硫胺素）
    var VitaminB2: String = ""//维生素 B2（核黄素）
    var VitaminB3: String = ""//维生素 B3（烟酸）
    var VitaminB5: String = ""//维生素 B5（泛酸）
    var VitaminB6: String = ""//维生素 B6（吡哆醇）
    var VitaminB7: String = ""//维生素 B7（生物素）
    var VitaminB9: String = ""//维生素 B9（叶酸）
    var VitaminB12: String = ""//维生素 B12（钴胺素）
    var VitaminC: String = ""//维生素 C（抗坏血酸）
    var VitaminA: String = ""//维生素 A（视黄醇）
    var VitaminD: String = ""//维生素 D
    var VitaminE: String = ""//维生素 E（生育酚）
    var VitaminK: String = ""//维生素 K（凝血维生素）

    fun getDataByPrimaryKey(itemId: Long) {
        newRx.add(
            Observable.create<DishBean>() {
                val app = application as AppApplication
                val dao = app.room!!.dishBeanDao()
                val bean = dao.queryByKey(itemId)
                it.onNext(bean)
            }.observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(
                    (Consumer<DishBean> { dish: DishBean ->
                        restoreData(dish)
                    }), (Consumer<Throwable> { throwable: Throwable? ->
                        showError("新增菜品失败")
                    })
                )
        )
    }

    private fun restoreData(dishBean: DishBean) {
        mBinding.name.setText(dishBean.name)
        mBinding.introduce.setText(dishBean.introduce)
        mBinding.taste.setText(dishBean.taste)
        mBinding.calorie.setText(dishBean.calorie)
        mBinding.protein.setText(dishBean.protein)
        mBinding.sugar.setText(dishBean.sugar)
        mBinding.fat.setText(dishBean.fat)
        mBinding.price.setText(dishBean.price)
        mBinding.purine.setText(dishBean.purine)
        mBinding.heat.setText(dishBean.heat)
        mBinding.dietaryFiber.setText(dishBean.dietaryFiber)
        mBinding.cholesterol.setText(dishBean.cholesterol)

        val stringListType: Type = object : TypeToken<List<String>>() {}.type
        healthTagList.clear()
        healthTagList.addAll(Gson().fromJson<List<String>>(dishBean.healthTag, stringListType))
        mBinding.healthTagRv.models = healthTagList
        if (dishBean.imagePath.isNotEmpty()) {
            setImageAddInVisible(dishBean.imagePath)
        } else {
            setImageAddVisible()
        }

        rawMaterialTagList.clear()
        rawMaterialTagList.addAll(
            Gson().fromJson<List<String>>(
                dishBean.rawMaterial,
                stringListType
            )
        )
        mBinding.rawMaterialTagRv.models = rawMaterialTagList

        mBinding.cookMethod.setText(dishBean.cookMethod)
        mBinding.cookSkill.setText(dishBean.cookSkill)
        iron = dishBean.iron
        manganese = dishBean.manganese
        zinc = dishBean.zinc
        copper = dishBean.copper
        potassium = dishBean.potassium
        phosphorus = dishBean.phosphorus
        sodium = dishBean.sodium
        calcium = dishBean.calcium
        selenium = dishBean.selenium
        magnesium = dishBean.magnesium
        VitaminB1 = dishBean.VitaminB1
        VitaminB2 = dishBean.VitaminB2
        VitaminB3 = dishBean.VitaminB3
        VitaminB5 = dishBean.VitaminB5
        VitaminB6 = dishBean.VitaminB6
        VitaminB7 = dishBean.VitaminB7
        VitaminB9 = dishBean.VitaminB9
        VitaminB12 = dishBean.VitaminB12
        VitaminC = dishBean.VitaminC
        VitaminA = dishBean.VitaminA
        VitaminD = dishBean.VitaminD
        VitaminE = dishBean.VitaminE
        VitaminK = dishBean.VitaminK
    }

    fun start(
        context: Context,
        primaryKey: Long
    ) {
        val starter =
            Intent(context, InputActivity::class.java)
        starter.putExtra("primaryKey", primaryKey)
        context.startActivity(starter)
    }
}